package cn.edu.xmu.orderpayment.order.controller;



import cn.edu.xmu.oomall.core.util.Common;
import cn.edu.xmu.oomall.core.util.ReturnNo;
import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.orderpayment.order.model.bo.Order;
import cn.edu.xmu.orderpayment.order.model.vo.SimpleOrderRetVo;
import cn.edu.xmu.orderpayment.order.model.vo.UpdateOrderVo;
import cn.edu.xmu.orderpayment.order.model.vo.NewOrderVo;
import cn.edu.xmu.orderpayment.order.service.CustomerOrderService;
import cn.edu.xmu.privilegegateway.annotation.aop.Audit;
import cn.edu.xmu.privilegegateway.annotation.aop.LoginName;
import cn.edu.xmu.privilegegateway.annotation.aop.LoginUser;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;

import static cn.edu.xmu.oomall.core.util.Common.decorateReturnObject;
import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;
import java.time.ZonedDateTime;

import static cn.edu.xmu.oomall.core.util.Common.processFieldErrors;
import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;

/**
 * @author Chencheng Liao 22920192204238
 * @date 2021/12/11
 */
@Api(value = "供用户访问的订单api")
@Validated
@RefreshScope
@RestController
@RequestMapping(value = "/", produces = "application/json;charset=UTF-8")
public class CustomerOrderController {

    @Autowired
    CustomerOrderService customerOrderService;

    @Autowired
    private HttpServletResponse httpServletResponse;

    /**
     * 获得订单所有状态
     *
     * @param
     * @return Object
     * @author Chencheng Liao 22920192204238
     * @Date 2021/12/11
     */
    @ApiOperation(value = "获取订单的所有状态", tags = "order")
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "成功")})
    @GetMapping(value = "/orders/states")
    public Object getOrderState() {
        ReturnObject returnObject = customerOrderService.getOrderStates();
        return Common.decorateReturnObject(returnObject);
    }

    /**
     * 买家查看查询名下的订单(概要)
     * @param loginUser
     * @param page
     * @param pageSize
     * @return object
     * @author Chencheng Liao 22920192204238
     * @Date 2021/12/13
     */
    @ApiOperation(value = "买家查询订单(概要查询)")
    @ApiImplicitParams({
            @ApiImplicitParam(name="authorization", value="Token", required = true, dataType="String", paramType="header"),
            @ApiImplicitParam(name="orderSn",value = "订单编号",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="state", value = "订单状态",required = false, dataType="Long", paramType="query"),
            @ApiImplicitParam(name="beginTime",value = "开始时间",required = false, dataType="String", paramType="query"),
            @ApiImplicitParam(name="endTime", value = "结束时间",required = false, dataType="String", paramType="query"),
            @ApiImplicitParam(name="page",value = "页码",required = false, dataType="Integer", paramType="query"),
            @ApiImplicitParam(name="pageSize",value = "每页数目",required = false, dataType="Integer", paramType="query")
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功"),
            @ApiResponse(code =504,message = "操作的资源id不存在")
    })
    @Audit(departName = "orders")
    @GetMapping(value = "/orders")
    public Object customerGetAllSimpleOrders(
            @LoginUser Long loginUser, @LoginName String loginUsername,
            @RequestParam(required = false) String orderSn,
            @RequestParam(required = false) Integer state,
            @RequestParam(required = false) @DateTimeFormat(pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSXXX") ZonedDateTime beginTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSXXX") ZonedDateTime endTime,
            @RequestParam(required = false,defaultValue = "1") Integer page,
            @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        if (beginTime != null && endTime != null && beginTime.isAfter(endTime)) {
            ReturnObject returnObjectNotValid = new ReturnObject(ReturnNo.LATE_BEGINTIME);
            return decorateReturnObject(returnObjectNotValid);
        }
        ReturnObject ret= customerOrderService.customerGetAllSimpleOrders(loginUser,orderSn,state,beginTime,endTime,page,pageSize);
        return Common.decorateReturnObject(Common.getPageRetVo(ret, SimpleOrderRetVo.class));
    }

    /**
     * 买家查询名下订单完整信息
     *
     * @return object
     * @author Chencheng Liao 22920192204238
     * @Date 2021/12/13
     */
    @ApiOperation(value = "买家查询名下订单完整信息", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = "authorization", value = "用户token", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "订单id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功"),
    })
    @Audit
    @GetMapping("orders/{id}")
    public Object customerGetAllOrders(@LoginUser @ApiIgnore Long userId, @PathVariable Long id){
        ReturnObject ret = customerOrderService.customerGetAllOrders(userId,id);
        return Common.decorateReturnObject(ret);
    }


    /**
     * @Description: 买家修改本人名下订单,只能修改未发货状态前的地址，如果已分单则同步更改状态
     * @Param: [id, loginUser, loginUserName, updateOrderVo, bindingResult]
     * @return: Object
     * @Author: Li Yixuan 22920192204232
     * @Date: 2021/12/13
     * @Modify: 2021/12/24
     */
    @ApiOperation(value = "买家修改本人名下订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "Token", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name="id",value="订单修id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUser",value="用户登录账号(id)",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUserName",value="用户登录名",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="updateOrderVo",value="订单修改信息",dataType = "UpdateOrderVo",paramType = "body"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功"),
            @ApiResponse(code = 507, message = "当前状态禁止此操作"),
            @ApiResponse(code = 801, message = "订单地址费用变化")
    })
    @Audit
    @PutMapping("orders/{id}")
    public Object modifyOrder(@PathVariable("id") Long id,
                              @LoginUser Long loginUser, @LoginName String loginUserName,
                              @Validated @RequestBody UpdateOrderVo updateOrderVo, BindingResult bindingResult){
        Object returnObject = processFieldErrors(bindingResult, httpServletResponse);
        if (null != returnObject) {
            return returnObject;
        }
        Order orderBo = cloneVo(updateOrderVo, Order.class);
        ReturnObject ret = customerOrderService.updateOrder(id, orderBo, loginUser, loginUserName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * @Description: 买家逻辑删除本人名下订单
     * @Param: [id, loginUser, loginUserName]
     * @return:
     * @Author: Li Yixuan 22920192204232
     * @Date:
     */
    @ApiOperation(value = "买家逻辑删除本人名下订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "Token", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name="id",value="订单修id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUser",value="用户登录账号(id)",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUserName",value="用户登录名",dataType = "String",paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功"),
            @ApiResponse(code = 507, message = "当前状态禁止此操作")
    })
    @Audit
    @DeleteMapping("orders/{id}")
    public Object deleteOrder(@PathVariable("id") Long id, @LoginUser Long loginUser, @LoginName String loginUserName) {
//        Object filedErrors = Common.processFieldErrors(bindingResult, httpServletResponse);
//        if (filedErrors != null)
//            return filedErrors;
        ReturnObject ret = customerOrderService.deleteOrder(id, loginUser, loginUserName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * @Description: 买家取消本人名下订单，取消所有关联订单
     * @Param: [id, loginUser, loginUserName]
     * @return: Object
     * @Author: Li Yixuan 22920192204232
     * @Date: 2021/12/16
     */
    @ApiOperation(value = "买家取消本人名下订单", tags = "order")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = "authorization", value = "用户Token", required = true),
            @ApiImplicitParam(name="id",value="订单id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUser",value="用户登录账号(id)",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUserName",value="用户登录名",dataType = "String",paramType = "query")})
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "成功"),
            @ApiResponse(code = 507, message = "当前状态禁止此操作")})
    @Audit(departName = "orders")
    @PutMapping(value = "/orders/{id}/cancel")
    public Object cancelOrder(@PathVariable("id") Long id, @LoginUser Long loginUser, @LoginName String loginUserName) {
        ReturnObject ret = customerOrderService.cancelOrder(id, loginUser, loginUserName);
        return Common.decorateReturnObject(ret);
    }


    /**
     * @Description: 买家标记确认收货,可对父子订单进行操作
     * @Param: [id, loginUser, loginUserName]
     * @return: Object
     * @Author: Li Yixuan 22920192204232
     * @Date: 2021/12/16
     */
    @ApiOperation(value = "买家标记确认收货", tags = "order")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = "authorization", value = "用户Token", required = true),
            @ApiImplicitParam(name="id",value="订单id",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUser",value="用户登录账号(id)",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="loginUserName",value="用户登录名",dataType = "String",paramType = "query")})
    @ApiResponses(value = {
            @ApiResponse(code = 0, message = "成功"),
            @ApiResponse(code = 507, message = "当前状态禁止此操作")})
    @Audit(departName = "orders")
    @PutMapping(value = "/orders/{id}/confirm")
    public Object customerConfirmOrder(@PathVariable("id") Long id, @LoginUser Long loginUser, @LoginName String loginUserName) {
        ReturnObject ret = customerOrderService.customerConfirmOrder(id, loginUser, loginUserName);
        return Common.decorateReturnObject(ret);
    }

    /**
     * 查询自己订单的支付信息
     *
     * @return object
     * @author Chencheng Liao 22920192204238
     * @Date 2021/12/22
     */
    @ApiOperation(value = "查询自己订单的支付信息", tags ="order")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = "authorization", value = "用户token", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "订单id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功"),
    })
    @GetMapping("orders/{id}/payment")
    @Audit
    public Object getOrderPayInfo(@PathVariable Long id,@LoginUser Long userId) {

        ReturnObject res = customerOrderService.getOrderPayInfo(id,userId);
        return decorateReturnObject(res);
    }

    /**
     * 查询自己订单的退款信息
     *
     * @return object
     * @author Chencheng Liao 22920192204238
     * @Date 2021/12/22
     */
    @ApiOperation(value = "查询自己订单的退款信息", tags ="order")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = "authorization", value = "用户token", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "订单id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 0, message = "成功"),
    })
    @GetMapping("orders/{id}/refund")
    @Audit
    public Object getOrderRefundInfo(@PathVariable Long id,@LoginUser Long userId) {

        ReturnObject res = customerOrderService.getOrderRefundInfo(id,userId);
        return decorateReturnObject(res);
    }

    /**
     * @Description: 买家申请建立订单 (普通，团购，预售)
     * @Param: [loginUser, loginUserName, newOrderVo, bindingResult]
     * @return: java.lang.Object
     * @Author: Li Yixuan 22920192204232
     * @Date: 2021/12/13
     * @Modify: 2021/12/25
     */
    @Audit
    @PostMapping("orders")
    public Object createOrder(@LoginUser Long loginUser, @LoginName String loginUserName,
                              @Validated @RequestBody NewOrderVo newOrderVo, BindingResult bindingResult){
        var filedErrors = Common.processFieldErrors(bindingResult, httpServletResponse);
        if (filedErrors != null)
            return filedErrors;

        ReturnObject ret;
        ret = customerOrderService.createMyselfOrder(newOrderVo,loginUser,loginUserName);
        if (ret.getCode() != ReturnNo.OK) {
            return decorateReturnObject(ret);
        }
        httpServletResponse.setStatus(HttpServletResponse.SC_CREATED);
        try {
            Object o = Common.decorateReturnObject(ret);
            return o;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return new ReturnObject<>(e.getMessage());
        }
    }
}
